/**
 * The MIT License
 *
 * Copyright (c) 2010 Benjamin Klum
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.helgoboss.executable_manager_ref_impl

import org.eclipse.scalamodules._
import org.osgi.framework.{BundleActivator, BundleContext}
import org.helgoboss.scala_logging_osgi.OsgiLogging
import java.io.{InputStream, FileOutputStream, IOException, File}
import org.helgoboss.win32_facade.{Win32Facade, PathScope}
import scala.collection.JavaConversions._
import org.helgoboss.executable_manager.ExecutableManager

object ExecutableManagerRefImpl {
    val ExecutablesDir = new File(System.getProperty("user.home") + "/.executable-manager/bin")
}

class ExecutableManagerRefImpl extends ExecutableManager with BundleActivator with OsgiLogging {
    
    import ExecutableManagerRefImpl._
    
    protected var bundleContext: BundleContext = _
    
    

    def installExecutable(fileName: String, inputStream: InputStream) {
        val file = new File(ExecutablesDir, fileName)
        val outputStream = new FileOutputStream(file)
        try {
            val buffer = new Array[Byte](0xFFFF)
            var eof = false
            while (!eof) {
                val length = inputStream.read(buffer)
                if (length == -1) {
                    eof = true
                } else {
                    outputStream.write(buffer, 0, length)
                }
            }
        } finally {
            outputStream.close
            inputStream.close
        }
        file.setExecutable(true)
    }
    
    def removeExecutable(fileName: String) {
        val file = new File(ExecutablesDir, fileName)
        if (file.exists) {
            file.delete
        }
    }
    
    def executableExists(fileName: String) = {
        val file = new File(ExecutablesDir, fileName)
        file.exists
    }
    
    
	def start(context: BundleContext) {
        bundleContext = context
        
        
        /* Make sure executable path exists */
        
        if (!ExecutablesDir.exists) {
            ExecutablesDir.mkdirs
        }
        
        
        /* Make sure it is on path */
        
        val executablesPathComponent = ExecutablesDir.getCanonicalPath
        
        val os = System.getProperty("os.name")
        
        if (os.startsWith("Windows")) {
            val currentPathComponents = Win32Facade.getPathVariableComponents(PathScope.USER)
            
            if (!currentPathComponents.contains(executablesPathComponent)) {
                Win32Facade.addToPathVariable(PathScope.USER, executablesPathComponent)
            }
        } else {
            /* TODO */
        }
        
        
        /* Register service */
        
        bundleContext createService (this, Map.empty, interface[ExecutableManager])
	}
    
	
	def stop(context: BundleContext) {
        bundleContext = null
	}
    
}